package org.jeecg.modules.hotel.belongToSkd.job;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.IdGeneratorSnowflake;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.YouBianCodeUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.school.entity.LwgyBaseSchool;
import org.jeecg.modules.basic.demo.school.mapper.LwgyBaseSchoolMapper;
import org.jeecg.modules.basic.demo.school.service.ILwgyBaseSchoolService;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.jeecg.modules.basic.entry.util.StringUtil;
import org.jeecg.modules.hotel.belongToSkd.entity.ReadStudentInfo;
import org.jeecg.modules.hotel.belongToSkd.service.ReadStudentInfoService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 *从数据中心获取学生基础信息，机构信息等
 * @author:SN
 * @date: 2022.08.22
 */

@Slf4j
public class ReadStudentInfoJob implements Job {

    @Autowired
    private ReadStudentInfoService readStudentInfoService;
    @Autowired
    private ILwgyBaseSchoolService lwgyBaseSchoolService;
    @Autowired
    private ILwgyBaseStudentService lwgyBaseStudentService;
    @Autowired
    private LwgyBaseSchoolMapper lwgyBaseSchoolMapper;
    @Autowired
    private IdGeneratorSnowflake snowflake;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("============进入定时器=============");
        int year = StringUtil.getCurrentYear();
        List<Map<String,String>> schoolList = readStudentInfoService.queryStuSchool(year);
        Set<LwgyBaseSchool> set = new HashSet<>(500);
        Map<String, String> map = new HashMap<>(500);
        String id = "";
        String xl="";
          for (Map<String,String> importSchool: schoolList) {
                id = "0";
                String campusName = "青岛校区";
                map = getSchoolInfo(set, id, campusName,null, "campus", map);
                String facultyName = importSchool.get("XYMC");
                map = getSchoolInfo(set, map.get("id"), facultyName, importSchool.get("XYDM"),"faculty", map);
                String gradeName = String.valueOf(importSchool.get("DQSZJ"));
                map = getSchoolInfo(set, map.get("id"), gradeName, null,"grade", map);
                String majorName = importSchool.get("ZYMC");
                map = getSchoolInfo(set, map.get("id"), majorName,  importSchool.get("ZYDM"),"major", map);
                String className = importSchool.get("BJMC");
                map = getSchoolInfo(set, map.get("id"), className,  importSchool.get("BJDM"),"class", map);
            }
        List<LwgyBaseSchool> lwgyBaseSchools = set.stream().filter(lwgyBaseSchool -> lwgyBaseSchool.isExistFlag() == false).collect(Collectors.toList());
        lwgyBaseSchoolService.saveBatch(lwgyBaseSchools);
        //所有学生的住宿信息，
        List<Map<String,String>> studentList = readStudentInfoService.queryStu(year);
        List<LwgyBaseStudent> lwgyBaseStudents = new ArrayList<>(studentList.size());
        Iterator<Map<String,String>> iterator = studentList.iterator();
        while (iterator.hasNext()) {
            Map<String,String> stuMap = iterator.next();
            LwgyBaseStudent lwgyBaseStudent = new LwgyBaseStudent();
            String key = new StringBuilder()
                    .append("青岛校区").append("_")
                    .append(stuMap.get("XYMC")).append("_")
                    .append(stuMap.get("DQZSJ")).append("_")
                    .append(stuMap.get("ZYMC")).append("_")
                    .append(stuMap.get("BJMC")).append(":").toString();
            LwgyBaseSchool lwgyBaseSchool = (LwgyBaseSchool) redisUtil.get(key);//获取缓存中的classId
            if (oConvertUtils.isEmpty(lwgyBaseSchool)) {//缓存中不存在
                lwgyBaseSchool = lwgyBaseSchoolService.getClassIdByName(lwgyBaseStudent);//从数据库获取对应的
                redisUtil.set(key, lwgyBaseSchool, 180);//并将classId放入缓存
            }
            if (oConvertUtils.isNotEmpty(lwgyBaseSchool)) {
                lwgyBaseStudent.setStudentClass(lwgyBaseSchool.getClassId());
                lwgyBaseStudent.setStudentMajor(lwgyBaseSchool.getMajorId());
                lwgyBaseStudent.setStudentYear(lwgyBaseSchool.getGradeId());
                lwgyBaseStudent.setStudentCollege(lwgyBaseSchool.getFacultyId());
                lwgyBaseStudent.setStudentCampus(lwgyBaseSchool.getCampusId());
            }

            lwgyBaseStudent.setStudentName(stuMap.get("XM"));
            lwgyBaseStudent.setStudentNumber(stuMap.get("XH"));
            lwgyBaseStudent.setStudentSex(stuMap.get("XBM"));
            lwgyBaseStudent.setStudentSchoolSystem(stuMap.get("XZ"));
            lwgyBaseStudent.setStudentIdcard(stuMap.get("SFZJH"));
            String bytime = stuMap.get("BYNF")+"-07-01 00:00:00";
            Date date = new Date();
            try{
                date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(bytime);
            }catch (Exception e){

            }
          switch (stuMap.get("CC")){
                case "本科" : xl = "bk";break;
                case "本科生" : xl = "bk";break;
                case "研究生" : xl = "yjs";break;
                case "专科" : xl = "zk";break;
                case "博士研究生" : xl = "bsyjs";break;
                case "校内专升本" : xl = "zsb";break;
                case "硕士研究生" : xl = "硕士研究生";break;
                case "中专" : xl = "zz";break;
                case "其他" : xl = "qt";break;

            }
            lwgyBaseStudent.setStudentLeaveschool(date);
            lwgyBaseStudent.setStudentTeacher(stuMap.get("fdyName"));
            lwgyBaseStudent.setStudentEducation(xl);
            lwgyBaseStudent.setStudentState("0");
            lwgyBaseStudents.add(lwgyBaseStudent);

        }
        List<String> stuNumber = new ArrayList<>(lwgyBaseStudents.size());
        lwgyBaseStudents.stream().forEach(item -> stuNumber.add(item.getStudentNumber()));//取出学生的学号
        QueryWrapper<LwgyBaseStudent> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "student_number");
        queryWrapper.in("student_number", stuNumber);
        List<LwgyBaseStudent> lwgyBaseStudentsNum = lwgyBaseStudentService.getBaseMapper().selectList(queryWrapper);//找出数据库中已经存在的学生
        lwgyBaseStudentsNum.forEach(lwgyBaseStudent -> {
            lwgyBaseStudents.stream()
                    .filter(item -> item.getStudentNumber().equals(lwgyBaseStudent.getStudentNumber()))
                    .forEach(item -> item.setId(lwgyBaseStudent.getId()));
        });
        lwgyBaseStudentService.saveOrUpdateBatch(lwgyBaseStudents);
    }

    private Map<String, String> getSchoolInfo(Set<LwgyBaseSchool> set, String id, String campusName,String dm,  String type, Map<String, String> map) {
        String pid = id;
        LwgyBaseSchool lwgyBaseSchool;
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", campusName);
        queryWrapper.eq("pid", id);
        queryWrapper.eq("del_flag", 0);
        List<LwgyBaseSchool> lwgyBaseSchools = lwgyBaseSchoolMapper.selectList(queryWrapper);
        String sysOrgCode = lwgyBaseSchoolMapper.getMaxSysOrgCode(pid);//查询最大的sysOrgCode
        String sysOrgCode1 = map.get(pid);
        if (oConvertUtils.isNotEmpty(sysOrgCode) && oConvertUtils.isNotEmpty(sysOrgCode1)) {//数据库和集合中的sysorgcode都不是空
            if (sysOrgCode.compareTo(sysOrgCode1) > 0) {//数据库中的大于于集合中的
                map.put(pid, sysOrgCode);//将集合中的更换为数据库中的
            }
        } else if (oConvertUtils.isEmpty(sysOrgCode)) {//数据库中的code为空
            map.put(pid, sysOrgCode1);//使用集合中的
        } else if (oConvertUtils.isEmpty(sysOrgCode1)) {//集合中的code为空
            map.put(pid, sysOrgCode);//使用数据库中的
        } else {//都为空
            sysOrgCode = "";
        }
        if (oConvertUtils.listIsEmpty(lwgyBaseSchools)) {
            lwgyBaseSchool = new LwgyBaseSchool();
            if (id == "0") {
                lwgyBaseSchool.setPid("0");
            } else {
                lwgyBaseSchool.setPid(id);
            }
            id = String.valueOf(snowflake.snowflakeId());//获取分布式的id
            lwgyBaseSchool.setId(id);
            lwgyBaseSchool.setName(campusName);
            lwgyBaseSchool.setDelFlag("0");
            lwgyBaseSchool.setHasChild("1");
            lwgyBaseSchool.setUniversityCode(dm);
            lwgyBaseSchool.setType(type);
            lwgyBaseSchool.setUniversitySort(type);
            List<LwgyBaseSchool> collect = set.stream().filter(lwgyBaseSchool1 -> lwgyBaseSchool1.getId().equals(pid)).collect(Collectors.toList());
            String pSysOrgCode = "";
            if (oConvertUtils.listIsNotEmpty(collect)) {
                LwgyBaseSchool lwgyBaseSchool1 = collect.get(collect.size() - 1);
                pSysOrgCode = lwgyBaseSchool1.getSysOrgCode();
            }
            sysOrgCode = YouBianCodeUtil.getSubYouBianCode(pSysOrgCode, map.get(pid));
            lwgyBaseSchool.setSysOrgCode(sysOrgCode);
            lwgyBaseSchool.setExistFlag(false);
        } else {
            lwgyBaseSchool = lwgyBaseSchools.get(0);
            sysOrgCode = lwgyBaseSchool.getSysOrgCode();
            lwgyBaseSchool.setExistFlag(true);
            id = lwgyBaseSchool.getId();
        }
        map.put(pid, sysOrgCode);//把最后的code放入map
        List<LwgyBaseSchool> schoolList = set.stream().filter(baseSchool ->
                baseSchool.getPid().equals(pid)).filter(baseSchool ->
                baseSchool.getName().equals(campusName)).collect(Collectors.toList());
        if (schoolList.size() <= 0) {
            set.add(lwgyBaseSchool);
        } else {
            id = schoolList.get(0).getId();
        }
        map.put("id", id);

        return map;
    }
}
